import json

from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify, current_app
from application import db
from flask_login import login_user, logout_user, login_required, current_user
from werkzeug.security import generate_password_hash, check_password_hash

from application.users.forms import RegisterForm, LoginForm, SelectClassForm
from application.users.models import Users, Class

users = Blueprint('users', __name__)


# 实际路由地址：/users/register
# 用户注册
@users.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm()
    # 验证表单
    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        fullname = form.fullname.data
        password_hash = generate_password_hash(password)
        # 创建新用户记录
        user = Users(username=username, password=password_hash, fullname=fullname)
        db.session.add(user)
        db.session.commit()

        # 自动登录
        login_user(user, remember=False)

        # 跳转页面--班级选择
        flash('Register Successful!')
        return redirect(url_for('users.select_class'))

    return render_template('users/register.html', form=form)


@users.route('/select_class', methods=['GET', 'POST'])
@login_required
def select_class():
    form = SelectClassForm()
    if form.validate_on_submit():
        current_user.class_id = form.select_class.data
        db.session.add(current_user)
        db.session.commit()

        class_name = Class.query.get(form.select_class.data).name
        flash(f'Welcome to join {class_name}!')
        return redirect(url_for('users.member_list'))

    return render_template('users/select_class.html', form=form)


@users.route('/logout')
def logout():
    logout_user()
    flash('Logout Successful!')
    return redirect(url_for('home.index'))


@users.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        username = form.username.data
        user = Users.query.filter_by(username=username).first()
        if user:
            password = form.password.data
            if check_password_hash(user.password, password):
                login_user(user, remember=form.remember_me)
                flash('login Successful!')
                if user.uclass:
                    return redirect(url_for('users.member_list'))
                return redirect(url_for('users.select_class'))
        flash('username or password error!')
    return render_template('users/login.html', form=form)


@users.route('/member_list')
@login_required
def member_list():
    return render_template('users/member_list.html')


# 改变user当前听课状态
@users.route('/change_listen_status', methods=['POST'])
def change_listen_status():
    json_data_str = request.get_data(as_text=True)
    json_data = json.loads(json_data_str)
    if 'listen_status' not in json_data:
        return jsonify({'status': 'missing parameter'})
    listen_status = json_data.get('listen_status')
    user_id = current_user.id
    current_user.current_listen_status = listen_status
    db.session.add(current_user)
    db.session.commit()
    color = Users.query.get(user_id).get_status()['color']
    return jsonify({'status': 'ok', 'user_id': user_id, 'color': color})


# 获取指定班级成员列表(json) [{}, {}, {}]
@users.route('/classmates/<int:class_id>')
@login_required
def classmates(class_id):
    classmates = Class.query.get(class_id).users
    result_list = [user.to_json() for user in classmates]
    return jsonify(result_list)


@users.route('/get_info')
def get_info():
    current_id = request.args.get('current_id')
    user = Users.query.get(int(current_id))
    status = user.current_listen_status
    return status


# 显示所有用户
@users.route('/all_users')
@login_required
def all_users():
    page = request.args.get('page', 1, type=int)
    sort_id = request.args.get('sort_id', 0)
    sort_type = request.args.get('sort_type', 0)
    if sort_id and sort_type:
        if sort_id == 'username':
            judge1 = request.args.get('judge1') if request.args.get('judge1') else 'False'
            judge1 = False if judge1 == 'True' else True
            judge2, judge3 = False, False
            arrows1 = '∧'if judge1 else '∨'
            arrows2, arrows3 = None, None
        elif sort_id == 'fullname':
            judge2 = request.args.get('judge2') if request.args.get('judge2') else 'False'
            judge2 = False if judge2 == 'True' else True
            judge1, judge3 = False, False
            arrows2 = '∧'if judge2 else '∨'
            arrows1, arrows3 = None, None
        else:
            judge3 = request.args.get('judge3') if request.args.get('judge3') else 'False'
            judge3 = False if judge3 == 'True' else True
            judge1, judge2 = False, False
            arrows3 = '∧'if judge3 else '∨'
            arrows2, arrows1 = None, None
    else:
        sort_id = 'id'
        sort_type = 'desc'
        judge1, judge2, judge3 = False, False, False
        arrows1, arrows2, arrows3 = None, None, None
    result = sort_id + sort_type
    sort = {'idasc': Users.id.asc(), 'iddesc': Users.id.desc(), 'usernamedesc': Users.username.desc(),
            'usernameasc': Users.username.asc(), 'fullnamedesc': Users.fullname.desc(),
            'fullnameasc': Users.fullname.asc(), 'createddesc': Users.created_time.desc(),
            'createdasc': Users.created_time.asc()}
    pagination = Users.query.order_by(sort[result]).paginate(
        page, per_page=current_app.config['COUNT_PER_PAGE'], error_out=False)
    users = pagination.items
    return render_template('users/all_users.html',
                           users=users, pagination=pagination, sort_id=sort_id, sort_type=sort_type,
                           judge1=judge1, judge2=judge2, judge3=judge3,
						   arrows1=arrows1, arrows2=arrows2, arrows3=arrows3)
